package demo.service.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import demo.vo.common.CachedObject;
import demo.service.CacheService;

@Service
public class LocalCacheService implements CacheService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ConcurrentMap<String, CachedObject> map = new ConcurrentHashMap<String, CachedObject>();

    @Override
    public void set(String key, Object value, long seconds) {
        if (key == null) {
            return;
        }
        try {
            map.put(key, new CachedObject(value, System.currentTimeMillis() + seconds * 1000));
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @Override
    public CachedObject get(String key) {
        if (key == null) {
            return null;
        }
        try {
            CachedObject cachedObject = map.get(key);
            if (cachedObject == null) {
                return null;
            }
            // 未过期
            if (System.currentTimeMillis() < cachedObject.getTimestamp()) {
                return cachedObject;
            }
            map.remove(key);
            return null;
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

}
